//
//  CJBasePopupInfo.m
//  CJUIKitDemo
//
//  Created by ciyouzen on 15/11/12.
//  Copyright (c) 2015年 dvlproad. All rights reserved.
//

#import "CJBasePopupInfo.h"
#import <objc/runtime.h>
#import "CJPopupBlankContainer.h"
#import "UIView+CJTapAction.h"
#import "UIView+CJPopupSuperviewSubview.h"

@implementation CJBasePopupInfo

static NSString * const cjTapViewKey = @"cjTapViewKey";

#pragma mark - 底层接口:弹出到视图View
/*
 *  将本View以size大小弹出到showInView视图中location位置
 *
 *  @param popupSuperview               弹出视图的父视图view
 *  @param popupView                    要被添加的视图
 *  @param popupViewOrigin              弹出视图的左上角origin坐标
 *  @param popupViewSize                弹出视图的size大小
 *  @param tapBlankViewCompleteBlock    点击空白区域后的操作(要自己执行cj_hidePopupView...来隐藏，因为有时候点击背景是不执行隐藏的)
 *
 *  @return 弹窗视图信息
 */
+ (CJBasePopupInfo *)addSubviewToPopupSuperview:(nonnull UIView *)popupSuperview
                                      popupView:(UIView *)popupView
                                     withOrigin:(CGPoint)popupViewOrigin
                                           size:(CGSize)popupViewSize
                               tapBlankComplete:(void(^ _Nullable)(void))tapBlankViewCompleteBlock
{
    CJBasePopupInfo *popupInfo = [self addSubviewToPopupSuperview:popupSuperview
                                                withBlankViewBelong:CJBlankViewBelongPopupView
                                                          popupView:popupView
                                                    popupViewOrigin:popupViewOrigin
                                                      popupViewSize:popupViewSize
                                                   tapBlankComplete:tapBlankViewCompleteBlock
                                  ];
    
    return popupInfo;
}

/*
 *  将当前视图弹出到视图view中央
 *
 *  @param popupSuperview               弹出视图的父视图view(可以为nil,为nil时候弹出到keyWindow上)
 *  @param popupView                    要被添加的视图
 *  @param popupViewSize                弹出视图的大小
 *  @param centerOffset                 弹窗弹出位置的中心与window中心的偏移量
 *  @param tapBlankViewCompleteBlock    点击空白区域后的操作(要自己执行cj_hidePopupView...来隐藏，因为有时候点击背景是不执行隐藏的)
 *
 *  @return 弹窗视图信息
 */
+ (CJBasePopupInfo *)addCenterSubviewToPopupSuperview:(nullable UIView *)popupSuperview
                                  popupView:(UIView *)popupView
                                   withSize:(CGSize)popupViewSize
                               centerOffset:(CGPoint)centerOffset
                           tapBlankComplete:(void(^ _Nullable)(void))tapBlankViewCompleteBlock
{
    if (popupSuperview == nil) {
        popupSuperview = [[UIApplication sharedApplication] keyWindow];
    }
    
    CGFloat popupSuperviewWidth = CGRectGetWidth(popupSuperview.frame);
    CGFloat popupSuperviewHeight = CGRectGetHeight(popupSuperview.frame);
    
    CGPoint popupViewShowCenter = CGPointMake(popupSuperviewWidth/2 + centerOffset.x,
                                              popupSuperviewHeight/2 + centerOffset.y);
    CGFloat originX = popupViewShowCenter.x - popupViewSize.width/2;
    CGFloat originY = popupViewShowCenter.y - popupViewSize.height/2;
    CGPoint popupViewOrigin = CGPointMake(originX, originY);
    
    CJBasePopupInfo *popupInfo = [self addSubviewToPopupSuperview:popupSuperview
                                                withBlankViewBelong:CJBlankViewBelongPopupView
                                                          popupView:popupView
                                                    popupViewOrigin:popupViewOrigin
                                                      popupViewSize:popupViewSize
                                                   tapBlankComplete:tapBlankViewCompleteBlock
                                  ];
    
    return popupInfo;
}


/*
 *  将当前视图弹出到视图view底部
 *
 *  @param popupSuperview               弹出视图的父视图view(可以为nil,为nil时候弹出到keyWindow上)
 *  @param popupView                    要被添加的视图
 *  @param popupViewHeight              弹出视图的高度
 *  @param edgeInsets                   弹窗与window的(左右下)边距
 *  @param tapBlankViewCompleteBlock    点击空白区域后的操作(要自己执行cj_hidePopupView...来隐藏，因为有时候点击背景是不执行隐藏的)
 *
 *  @return 弹窗视图信息
 */
+ (CJBasePopupInfo *)addBottomSubviewToPopupSuperview:(nullable UIView *)popupSuperview
                                            popupView:(UIView *)popupView
                                           withHeight:(CGFloat)popupViewHeight
                                           edgeInsets:(UIEdgeInsets)edgeInsets
                                     tapBlankComplete:(void(^ _Nullable)(void))tapBlankViewCompleteBlock
{
    if (popupSuperview == nil) {
        popupSuperview = [[UIApplication sharedApplication] keyWindow];
    }
    
    CGFloat popupViewWidth = CGRectGetWidth(popupSuperview.frame) - edgeInsets.left - edgeInsets.right;
    CGSize popupViewSize = CGSizeMake(popupViewWidth, popupViewHeight);
    
    CGFloat popupViewX = edgeInsets.left;
    CGFloat popupViewShowY = CGRectGetHeight(popupSuperview.frame) - popupViewHeight - edgeInsets.bottom;
    CGPoint popupViewOrigin = CGPointMake(popupViewX, popupViewShowY);
    
    CJBasePopupInfo *popupInfo = [self addSubviewToPopupSuperview:popupSuperview
                                                withBlankViewBelong:CJBlankViewBelongPopupView
                                                          popupView:popupView
                                                    popupViewOrigin:popupViewOrigin
                                                      popupViewSize:popupViewSize
                                                   tapBlankComplete:tapBlankViewCompleteBlock
                                  ];
    
    return popupInfo;
}


#pragma mark - Private Method
/*
 *  将本View以size大小添加到showInView视图中location位置
 *
 *  @param popupSuperview               弹出视图的父视图view
 *  @param blankViewBelong              blankView用哪个视图的属性来标记
 *  @param popupView                    要被添加的视图
 *  @param popupViewOrigin              弹出视图的左上角origin坐标
 *  @param popupViewSize                弹出视图的size大小
 *  @param tapBlankViewCompleteBlock    点击空白区域后的操作(要自己执行cj_hidePopupView...来隐藏，因为有时候点击背景是不执行隐藏的)
 */
+ (CJBasePopupInfo *)addSubviewToPopupSuperview:(nonnull UIView *)popupSuperview
                            withBlankViewBelong:(CJBlankViewBelong)blankViewBelong
                                      popupView:(UIView *)popupView
                                popupViewOrigin:(CGPoint)popupViewOrigin
                                  popupViewSize:(CGSize)popupViewSize
                               tapBlankComplete:(void(^ _Nullable)(void))tapBlankViewCompleteBlock
{
    if (CGSizeEqualToSize(popupView.frame.size, popupViewSize)) {
        NSLog(@"Warning:popupView视图大小将自动调整为指定的弹出视图大小");
        CGRect selfFrame = popupView.frame;
        selfFrame.size = popupViewSize;
        popupView.frame = selfFrame;
    }
    
    // popupView改成添加到blankView中
    CGRect popupViewShowFrame = CGRectMake(popupViewOrigin.x, popupViewOrigin.y,
                                           popupViewSize.width, popupViewSize.height);
    NSAssert(popupViewShowFrame.size.width != 0 && popupViewShowFrame.size.height != 0, @"弹出视图的宽高都不能为0");
    
    
    CJBasePopupInfo *popupInfo = [self addSubviewForPopupSuperview:popupSuperview
                                                 withBlankViewBelong:blankViewBelong
                                                           popupView:popupView
                                                    tapBlankComplete:tapBlankViewCompleteBlock];
    popupInfo.popupViewShowFrame = popupViewShowFrame;
    
    return popupInfo;
}


/*
 *  在popupSuperview上添加BlankView和popupView
 *
 *  @param popupSuperview           被添加到的地方
 *  @param blankViewBelong          blankView用哪个视图的属性来标记
 *  @param popupView                要被添加的视图
 *
 *  @return 添加的blankView和popupView
 */
+ (CJBasePopupInfo *)addSubviewForPopupSuperview:(UIView *)popupSuperview
                             withBlankViewBelong:(CJBlankViewBelong)blankViewBelong
                                       popupView:(UIView *)popupView
                                tapBlankComplete:(void(^ _Nullable)(void))tapBlankViewCompleteBlock
{
    if ([popupSuperview.subviews containsObject:popupView]) {
        return nil;
    }
    
    /* 1、popupSuperview添加空白的点击区域blankView */
    UIView *blankView;
    if (blankViewBelong == CJBlankViewBelongPopupView) {
        blankView = objc_getAssociatedObject(popupView, &cjTapViewKey);
    } else if (blankViewBelong == CJBlankViewBelongSuper) {
        blankView = objc_getAssociatedObject(popupSuperview, &cjTapViewKey);
    } else {
        blankView = objc_getAssociatedObject(popupView, &cjTapViewKey);
    }
    
    if (blankView == nil) { // 确保只有一个背景（否则弹出多个弹窗，容易叠加）
        blankView = [[CJPopupBlankContainer alloc] initWithTapBlankHandle:tapBlankViewCompleteBlock];
        
        [self cjPopup_makeView:popupSuperview addSubView:blankView withEdgeInsets:UIEdgeInsetsZero];
//        [popupSuperview addSubview:blankView];
//        CGFloat blankViewWidth = CGRectGetWidth(popupSuperview.frame);
//        CGFloat blankViewHeight = CGRectGetHeight(popupSuperview.frame);
//        CGRect blankViewFrame = CGRectMake(0, 0, blankViewWidth, blankViewHeight);
//        [blankView setFrame:blankViewFrame];    // blankView直接添加上去，popupView的Frame才用来控制动画
        
        [popupSuperview addPopupContainer:blankView];
    }
    popupView.cjTapBlankViewCompleteBlock = tapBlankViewCompleteBlock;
    
    if (blankViewBelong == CJBlankViewBelongPopupView) {
        objc_setAssociatedObject(popupView, &cjTapViewKey, blankView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    } else if (blankViewBelong == CJBlankViewBelongSuper) {
        objc_setAssociatedObject(popupSuperview, &cjTapViewKey, blankView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    } else {
        objc_setAssociatedObject(popupView, &cjTapViewKey, blankView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    /* 2、blankView添加popupView */
    [blankView addSubview:popupView];   // popupView改成添加到blankView中
    
    CJBasePopupInfo *popupInfo = [[CJBasePopupInfo alloc] init];
    popupInfo.blankView = blankView;
    popupInfo.popupView = popupView;
    
    return popupInfo;
}


+ (void)cjPopup_makeView:(UIView *)superView addSubView:(UIView *)subView withEdgeInsets:(UIEdgeInsets)edgeInsets {
    [superView addSubview:subView];
    subView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [superView addConstraint:
     [NSLayoutConstraint constraintWithItem:subView
                                  attribute:NSLayoutAttributeLeft   //left
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:superView
                                  attribute:NSLayoutAttributeLeft
                                 multiplier:1
                                   constant:edgeInsets.left]];
    
    [superView addConstraint:
     [NSLayoutConstraint constraintWithItem:subView
                                  attribute:NSLayoutAttributeRight  //right
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:superView
                                  attribute:NSLayoutAttributeRight
                                 multiplier:1
                                   constant:edgeInsets.right]];
    
    [superView addConstraint:
     [NSLayoutConstraint constraintWithItem:subView
                                  attribute:NSLayoutAttributeTop    //top
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:superView
                                  attribute:NSLayoutAttributeTop
                                 multiplier:1
                                   constant:edgeInsets.top]];
    
    [superView addConstraint:
     [NSLayoutConstraint constraintWithItem:subView
                                  attribute:NSLayoutAttributeBottom //bottom
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:superView
                                  attribute:NSLayoutAttributeBottom
                                 multiplier:1
                                   constant:edgeInsets.bottom]];
}


@end
